//对于axios进行二次封装
import axios from "axios";
//引入进度条
import nprogress from "nprogress";
//引入样式
import "nprogress/nprogress.css"

import cookie from "js-cookie";
//1.利用axios对象的方法create,创建axios实例

const requests = axios.create({
    //配置对象
    baseURL: "/api-integrated",
    //请求超时时间
    timeout: 5000,

});

//请求拦截器，发送请求之前，请求拦截器进行检测做事情
requests.interceptors.request.use((config) => {
    //进度条请求开始
    nprogress.start();
    let token = cookie.get('token')
    if (token) {
        config.headers['token'] = token
    }
    //console.log(config);
    //config为配置对象，有header请求头
    return config;
})

//响应拦截器
requests.interceptors.response.use(
    (response) => {
        //响应拦截器处理导出为excel数据的情况
        if (response.data.type != undefined) {
            nprogress.done();
            return response.data;
        }
        if (response.data.code === 200) {
            //进度条请求结束
            nprogress.done();
            return response.data
        } else if (response.data.code === -211) {
            console.log('先登录')
            window.location.href = '/'
            nprogress.done();
        }
    },
    (error) => {
        Message({
            message: response.data.message,
            type: 'error',
            duration: 5 * 1000,
        })
        //服务器响应失败后的数据回调
        return Promise.reject(new Error('fail'))
    }
)

//对外暴露
export default requests;